#!/usr/bin/python
# -*- coding: gb2312 -*-

import SocketServer, time
import os, time, sys, thread, pdb, logging, re, math
import Image, ImageChops, ImageStat, colorsys
from math import cos, sin, radians
import wx
import wx.lib.dragscroller

from socket import *

myHost = ""
myPort = 51769

BUFSZ = 1024
DET = 5

def now():
    return time.ctime(time.time())

# logger
logger = logging.getLogger('gmapcaten')
__hdlr = logging.FileHandler('gmapcaten.log')
__formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
__hdlr.setFormatter(__formatter)
logger.addHandler(__hdlr)
logger.setLevel(logging.DEBUG)

__olderror = logger.error
def __newerror(*karg, **kargs):
    __olderror(*karg, **kargs);
    exc = pdb.traceback.format_exc()
    if exc:
        __olderror(exc)
        print exc

logger.error = __newerror    

def ptw(pil, alpha=True):
    image = wx.EmptyImage(*list(pil.size))
    image.SetData(pil.convert('RGB').tostring())    
    if alpha:
        image.SetAlphaData(pil.convert('RGBA').tostring()[3::4])
    return image

def wtp(wimg):
    pil = Image.new('RGB', (wimg.GetWidth(), wimg.GetHeight()))
    pil.fromstring(wimg.GetData())
    return pil

#            pdc.DrawBitmap(wx.BitmapFromImage(ptw(pp)), 0,0)

def genCompImg(dropfile, bngname, host=None):
    img = Image.open(dropfile).convert('L')
    bng = Image.open(bngname).convert('L')
    outfile = dropfile.replace('.jpg','_comp.jpg')
    dataname = dropfile.replace('.jpg','.txt')
    if os.path.exists(outfile) and os.path.getmtime(outfile) >= os.path.getmtime(dropfile):
        return outfile        
    if host:
        if readfile(host, dataname)==0:
            sendfile(host, dropfile, bngname)
            readfile(host, dataname)
        datafile = open(dataname, 'r')
        lst = None
        for l in datafile.readlines():
            l = l.strip()
            if l.startswith('#'):
                continue
            lst = eval(l)
            break
        if lst==None:
            assert False, 'nothing read from %s'%dataname
        genblockfromlist(img, lst).save(outfile)
    else:
        if not os.path.exists(outfile):
            flypos.findit(img, bng).save(outfile)
        elif os.path.getmtime(outfile) < os.path.getmtime(dropfile):
            flypos.findit(img, bng).save(outfile)
    return outfile

def genblock(img):
    black = Image.new('RGB',img.size)
    img = img.convert('L')
    for xb in range(0, img.size[0], DET):
        for yb in range(0, img.size[1], DET):
            crp = img.crop((xb,yb,xb+DET,yb+DET))
            stat = ImageStat.Stat(crp)
            if stat.rms[0] > 50:
                black.paste((255,0,0),(xb,yb,xb+DET,yb+DET))
            if stat.sum[0] > 1000:
                black.paste((0,255,0),(xb,yb,xb+DET,yb+DET))
            if stat.stddev[0] > 50:
                black.paste((0,0,255),(xb,yb,xb+DET,yb+DET))
    return black

def genblockfromlist(img, ls):
    black = Image.new('RGB',img.size)
    img = img.convert('L')
    for it in ls:
        if it[2]==0:
            black.paste((255,0,0), (it[0],it[1],it[0]+DET,it[1]+DET))
        if it[2]==1:
            black.paste((0,255,0), (it[0],it[1],it[0]+DET,it[1]+DET))
        if it[2]==2:
            black.paste((0,0,255), (it[0],it[1],it[0]+DET,it[1]+DET))
    ret = black
    maskband = Image.new('L', img.size,150)
    ret.paste(img,mask=maskband)
    ret2 = Image.new('RGB', (img.size[0]*2,img.size[1]))
    ret2.paste(ret,(0,0))
    ret2.paste(img,(img.size[0], 0))
    return ret2

def findit(img, bng=None):
    if not bng:
        bng = background
    diff = ImageChops.subtract(bng, img).convert('L')
    ret = genblock(diff)
    maskband = Image.new('L', img.size,150)
    ret.paste(img,mask=maskband)
    ret2 = Image.new('RGB', (img.size[0]*2,img.size[1]))
    ret2.paste(ret,(0,0))
    ret2.paste(bng,(img.size[0], 0))
    return ret2

def err_use():
    print 'usage: %s [-c filetosend host -[r|s]]'
    sys.exit(1)
BASE  = 80.0    # sizes used in shapes drawn below
BASE2 = BASE/2
BASE4 = BASE/4



def fromhtml(fin):
    imglist = []
    for l in fin.readlines():
        l = l.strip()
        mt = re.findall('(kh_?\d*)\.jpg',l)
        if mt:
            imglist+=mt
    return imglist

def genImages(html):
    f = open(html,'r')
    prefix = html[:html.find('.htm')]+'_files/'
    postfix = '.jpg'
    big = None
    lst = fromhtml(f)
    sq = int(math.sqrt(len(lst)))
    sm = Image.open(prefix+'kh.jpg')
    sz = sm.size
    big = Image.new('RGB', (sm.size[0]*sq,sm.size[1]*sq))
    for ind in range(len(lst)):
        imgname = prefix + lst[ind]+ postfix
        del sm
        sm = Image.open(imgname)
        big.paste(sm, (sz[0]*(ind%sq), sz[1]*(ind/sq)))
    big.save('big.jpg')
    f.close()
    return big

class DrawPanel(wx.ScrolledWindow):
    """Draw a line to a panel."""
    def __init__(self, *karg, **kargs):
        wx.ScrolledWindow.__init__(self, *karg, **kargs)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown)
        self.Bind(wx.EVT_RIGHT_UP, self.OnRightUp)

        big = genImages('tiananmen.html')
        self.bg_bmp = wx.BitmapFromImage(ptw(big))
        
        self.SetScrollbars(1,1,big.size[0],big.size[1],0,0)
        self.scroller = wx.lib.dragscroller.DragScroller(self)

    def OnPaint(self, evt):
        dc = wx.PaintDC(self)
        self.DoPrepareDC(dc)
        dc.DrawBitmap(self.bg_bmp, 0,0)        
            
    def OnClose(self, evt):
        self.Show(False)
        self.Destroy()
        
    def OnRightDown(self, event):
        self.scroller.Start(event.GetPosition())

    def OnRightUp(self, event):
        self.scroller.Stop()

if __name__ == '__main__':

    app = wx.PySimpleApp(0)
    frame = wx.Frame(None, -1, "drag it", style = wx.DEFAULT_FRAME_STYLE)
    mainp = DrawPanel(frame)
    frame.Show(True)
##    frame.Maximize()
    app.MainLoop()

